<template>
  <div :class="className" :style="{height:height,width:width,}" />

</template>

<script>
require('echarts/theme/macarons') // echarts theme
import resize from './mixins/resize'

export default {
name: "HLineChart",
  mixins: [resize],
  props: {
    className: {
      type: String,
      default: 'chart'
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '18.75rem'
    },
    autoResize: {
      type: Boolean,
      default: true
    },
    chartData: {
      type: Object,
      required: true
    }
  },

  data() {
    return {
      chart: null
    }
  },
  watch: {
//观察chartData的变化
    chartData: {
      handler(newVal, oldVal) {
        if (this.chart) {
          if (newVal) {
            this.setOptions(newVal)
          } else {
            this.setOptions(oldVal)
          }
        } else {
          this.initChart();
        }
      },
      deep: true //对象内部属性的监听，关键。
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.initChart()
    })
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    this.chart.dispose()
    this.chart = null
  },
  methods: {
    initChart() {
      this.chart = this.$echarts.init(this.$el, 'macarons')
      this.setOptions(this.chartData)
    },
    setOptions({ expectedData, actualData } = {}) {
      this.chart.setOption({
        title: {
          text: '评估报告总量',
          subtext: '数据来自数据库'
        },
        tooltip: {
          trigger: 'axis',
          backgroundColor: '#fff',
          axisPointer: {
            type: 'shadow'
          }
        },
        legend: {
          data: ['正评', '预评']
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'value',
          boundaryGap: [0, 0.01]
        },
        yAxis: {
          type: 'category',
          data: ['2016', '2017', '2018', '2019', '2020', '2021']
        },
        series: [
          {
            name: '正评',
            type: 'bar',
            data: expectedData
          },
          {
            name: '预评',
            type: 'bar',
            data: actualData
          }
        ]
      })
    }
  }
}
</script>

<style scoped>

</style>